<?php
/**
 * 用户分类管理,需要登录进入
 * @author arlonzou
 *
 */
class UserCatesController extends AppController {

	var $name = 'UserCate';
	public $layout = 'user_default';
	
    var $components = array(
        'Auth',
    );
	
    public function add($model='Note') {
        
        if($_REQUEST['model']) {
            $model = $_REQUEST['model'];
        }
    	
    	$this->pageTitle = __('Add '.$model.' Category');
    	
        $this->set('cate_model',$model);
        $parents = $this->UserCate->getCateList($model,$this->currentUser['id']);
        $this->set('parents', $parents);
//         $this->_genParentList($model);
    	if (!empty($this->data)  && empty($this->data['UserCate']['model'])) {
    		$this->data['UserCate']['model']= $model;
    	}
    	parent::add();
    	if($this->insert_id) {
    	    $cache_key = 'model_cate_'.$this->data['UserCate']['model'].'_'.$this->data['UserCate']['creator'];
    	    Cache::delete($cache_key);
    	}
    }
    
    public function delete($id){
        $this->autoRender = false;
        $this->autoLayout = false;
        if(empty($id)) {
            $id = $_REQUEST['id'];
        }
        if( $id > 0 && $this->currentUser['id'] ) {
            /* ########### 重要： callback参数必需为false，否则会查询一次单个id删除。独特的双主键形式，造成错误。#############################*/
            $this->{$this->modelClass}->deleteAll(array('id' => $id, 'creator' => $this->currentUser['id']),false,false);
            echo json_encode(array('ret'=>0,'msg'=> __('Delete Successfully')));
        }
        else{
            echo json_encode(array('ret'=>-1,'msg'=> __('Delete Error')));
        }        
        exit;
    }
    
    
    public function edit($id) {
        
        $modelClass = $this->modelClass;
    	
    	if(!empty($this->data['UserCate']['parent_id']) && $this->data['UserCate']['parent_id'] == $id){
    		$this->data['UserCate']['parent_id'] = NULL;
    	}
    	

    	$datainfo = $this->{$this->modelClass}->find('first', array(
    	    'conditions' => array('id' => $id, 'creator' => $this->currentUser['id']),
    	    'recursive' => 1,
    	));
    	if (empty($datainfo)) {
    	    throw new ForbiddenException(__('You cannot edit this data'));
    	}
    	
    	if( !empty($this->data) ) {
    	    if( empty($this->data[$modelClass]['id']) ) {
    	        $this->data[$modelClass]['id'] = $id;
    	    }
    	    $this->autoRender = false;
    	    $this->data[$modelClass]['creator'] = $this->currentUser['id'];
    	    
    	    $keys = array_keys($this->{$modelClass}->schema());
    	    
    	    $arr = array();
    	    foreach($this->data[$modelClass] as $key => $val) {
    	        if(in_array($key,$keys) ) {
    	            if($key == 'parent_id' && empty($val)) {
    	                $arr[$key] = null;
    	            }
    	            else{
    	                $arr[$key] = $this->{$modelClass}->escape_string($val);
    	            }
    	        }
    	    }
    	    $this->{$this->modelClass}->updateAll($arr,array( 'id' => $id,'creator'=> $this->currentUser['id'] ));
    	    
    	    $successinfo = array('ret'=>0,'success' => __('Edit success'), 'actions' => array('OK' => 'closedialog'));
    	    
    	    if ($this->RequestHandler->accepts('json') || $this->RequestHandler->isAjax() || isset($_REQUEST['inajax'])) {
    	        $this->ajaxOutput($successinfo);
    	    }
    	    
    	    $redirect = $this->data[$this->modelClass]['referer'] ? $this->data[$this->modelClass]['referer'] : ($_REQUEST['referer'] ? $_REQUEST['referer'] : $this->Session->read('Auth.redirect'));
    	    if(empty($redirect)){
    	        if($_SERVER['HTTP_REFERER']) {
    	            $urls = parse_url($_SERVER['HTTP_REFERER']);
    	            if(!empty($urls['query'])  && is_array($urls['query']) ) {
    	                $redirect = $urls['path'].'?'.http_build_query($urls['query']);
    	            }
    	            else {
    	                $redirect = $urls['path'];
    	            }
    	        }
    	        else{
    	            $redirect = '/';
    	        }
    	    }
    	    $this->redirect($redirect);
    	}
    	else{
    	    $this->data = $datainfo; //加载数据到表单中
    	    $this->set('id',$id);
    	    $this->__loadFormValues($modelClass);
    	}
    	$this->set('cate_model',$this->data['UserCate']['model']);
    	$parents = $this->UserCate->getCateList($this->data['UserCate']['model'],$this->currentUser['id'],$id);
    	$this->set('parents', $parents);
    	
    	$this->pageTitle = __('Edit '.$this->modelClass);
    	$this->__viewFileName = 'add';
//     	$this->_genParentList($this->data['UserCate']['model'],$id);
    }

    public function getUserCates($modelClass) {
        $cates = $this->UserCate->getCateList($modelClass,$this->currentUser['id'],'',true);
        echo json_encode($cates);
        exit;
    }
    /**
     * 用户分类最多显示30个。
     */
	public function mine(){
	    
	    $this->pageTitle = '我的分类';
        
        $pagesize = intval(Configure::read($this->modelClass.'.pagesize'));
        if(!$pagesize){
            $pagesize = 50;
        }
        if(count($this->currentUser['role_id']) > 1) {
            $pagesize = 100;
        }
        
        $conditions = array('creator' => $this->currentUser['id']);
        
        if($_REQUEST['model']){
        	$conditions['model'] = $_REQUEST['model'];
        }
        
        $datalist = $this->{$this->modelClass}->find('threaded', array(
                'conditions' => $conditions,
                'limit'=> $pagesize,
        ));
        
        // $total = $this->{$this->modelClass}->find('count', array('conditions' => array('brand_id' => $this->brand['Brand']['id'])));
        // $datalist = $this->{$this->modelClass}->find('all', array(
        //         'conditions' => array('brand_id' => $this->brand['Brand']['id']),
        //         'fields'=>array('id','name','price','published','coverimg'),
        // ));
        
        // $page_navi = getPageLinks($total, $pagesize, '/user_cates/mine', $page);
        $this->set('datalist',$datalist);
        // $this->set('page_navi', $page_navi);
    }


}
?>